import json
import xml
import xml.etree.ElementTree as ET
import math

# 全局变量，关卡总孔数
g_total_hole_count=0
# 盘子容器的高度，用于将Inkscape坐标转换为cocos2d坐标
g_container_height = 720

# 读取一个盘子的孔位
def readPlateHolesData( rootDir , plate_name):
    global g_total_hole_count
    hole_arr = []
    plate_kongwei_name = plate_name.replace('.png', '_kongwei.svg')
    tree = ET.parse(rootDir + plate_kongwei_name)
    root = tree.getroot()
    groupElement = root.find('{http://www.w3.org/2000/svg}g')
    plateWidthInMM = float(root.get("viewBox").split(' ')[2])
    plateWidthInPx = float(root.get("width"))
    plateHeightInPx = float(root.get("height"))
    mm2px = plateWidthInPx / plateWidthInMM
    for imageElement1 in groupElement:
        imgName = imageElement1.get('{http://www.w3.org/1999/xlink}href')
        if( 'jewel' in imgName):
            holeXInPlate = float(imageElement1.get('x'))
            holeYInPlate = float(imageElement1.get('y'))
            holeWidthInPlate = float(imageElement1.get('width'))
            holeHeightInPlate = float(imageElement1.get('height'))
            hole1={}
            hole1["x"] = round(holeXInPlate * mm2px,0)
            hole1["width"] = round(holeWidthInPlate * mm2px,0)
            hole1["height"] = round(holeHeightInPlate * mm2px,0)
            hole1["y"] = plateHeightInPx - round(holeYInPlate * mm2px, 0) - hole1["height"] # 这里转换y为cc2d坐标（左下角）
            g_total_hole_count=g_total_hole_count+1
            hole_arr.append(hole1)
    return hole_arr


# 读取一个模板中的盘子数据
def readTemplateData( rootDir, template_name ):
    template_data = {}
    template_data["name"] = template_name

    plate_arr = []
    tree = ET.parse(rootDir+template_name)
    root = tree.getroot()
    groupElement = root.find('{http://www.w3.org/2000/svg}g')
    templateWidthInMM = float(root.get("viewBox").split(' ')[2])
    templateWidthInPx = float(root.get("width"))
    mm2px = templateWidthInPx / templateWidthInMM # inscape的svg采用mm单位，这里为mm转换px的换算系数

    [vbx,vby,vbw,vbh] = root.get("viewBox").split(' ')
    template_data["x"] =      round(float(vbx) * mm2px, 0)
    template_data["y"] =      round(float(vby) * mm2px, 0) # 模板坐标永远于容器坐标对齐，所以这里不用切换左下角，保持0，0坐标即可。
    template_data["width"] =  round(float(vbw) * mm2px, 0)
    template_data["height"] = round(float(vbh) * mm2px, 0)

    for imageElement1 in groupElement:
        plateName = imageElement1.get('{http://www.w3.org/1999/xlink}href')
        plateXInTem = float(imageElement1.get('x'))
        plateYInTem = float(imageElement1.get('y'))
        plate1 ={}
        plate1["name"] = plateName
        plate1["x"] = round(plateXInTem * mm2px,0)  # inkscape 坐标原点是左上角，
        plate1["width"] = round(float(imageElement1.get('width')) * mm2px, 0)  # inkscape 坐标原点是左上角，
        plate1["height"] = round(float(imageElement1.get('height')) * mm2px, 0)  # 这里也采用左上角坐标
        plate1["y"] = template_data["height"] - round(plateYInTem * mm2px, 0) - plate1["height"]  # 这里转换y为cc2d坐标（左下角）
        plate_arr.append(plate1)

    template_data["plates"] = plate_arr
    return template_data


# 输出全部孔位到JSON


# 读取关卡Level JSON数据
def readLevelJson(filename):
    with open(filename, 'r') as file:
        data = json.load(file)
        return data["layers"]
    return []

####################################################
# 入口程序 #####
rootDir="../"
layer_name_array = readLevelJson(rootDir+"level1.json")
outputName = "level1_out.json"
print(layer_name_array)
level_data = {}
level_data["layers"] = []
for layerName1 in layer_name_array:
    template_data = readTemplateData( rootDir , layerName1)
    layer_data = template_data
    for plate1 in layer_data["plates"]:
        hole_arr = readPlateHolesData( rootDir , plate1["name"] )
        plate1["holes"] = hole_arr
    level_data["layers"].append(layer_data)
print("total_hole_count ", g_total_hole_count)
mod3 = g_total_hole_count%3
print("mod3 " , mod3)
if(mod3 != 0 ):
    print("宝石总数量不能被三整除，关卡能够生成，但是无效。")
json.dump(level_data, open(rootDir+outputName,"w"))
